<template>
  <a-card title="数据采集" :bordered="false">
    <a-row :gutter="24" style="height: 400px;">
      <!-- 左侧上传区域 -->
      <a-col :span="12" class="left-section">
        <div class="upload-section">
          <a-upload-dragger
            v-model:fileList="fileList"
            :before-upload="beforeUpload"
            @change="handleChange"
            name="file"
            :multiple="true"
            accept="image/*"
          >
            <p class="ant-upload-drag-icon">
              <cloud-upload-outlined />
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p class="ant-upload-hint">支持批量上传钢材表面图片</p>
          </a-upload-dragger>
        </div>
      </a-col>

      <!-- 右侧预览区域 -->
      <a-col :span="12" class="right-section">
        <div v-if="fileList.length > 0" class="preview-section">
          <a-carousel
            v-if="fileList.length > 1"
            ref="carouselRef"
            :autoplay="false"
            :dots="false"
            :after-change="handleSlideChange"
            class="custom-carousel"
          >
            <div v-for="(file, index) in fileList" :key="index" class="carousel-item">
              <img :src="getImageUrl(file)" alt="预览" class="preview-image" />
            </div>
          </a-carousel>
          <img v-else :src="getImageUrl(fileList[0])" alt="预览" class="single-image" />

          <!-- 导航控件 -->
          <div v-if="fileList.length > 1" class="carousel-controls">
            <a-button
              class="nav-button prev-button"
              :disabled="currentSlide === 0"
              @click="handlePrev"
            >
              <left-outlined />
            </a-button>
            <div class="pagination">
              {{ currentSlide + 1 }} / {{ fileList.length }}
            </div>
            <a-button
              class="nav-button next-button"
              :disabled="currentSlide === fileList.length - 1"
              @click="handleNext"
            >
              <right-outlined />
            </a-button>
          </div>
        </div>
        <div v-else class="empty-preview">
          <p>请上传图片以预览</p>
        </div>
        <div class="start-button">
          <a-button :loading="uploading" @click="handleStart" type="primary">立即开始</a-button>
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { CloudUploadOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
import type { Carousel } from 'ant-design-vue'
import { createDetectionUsingPost } from '@/api/yoloController.ts'
import { useRouter } from 'vue-router'

const uploading = ref(false)
const router = useRouter();

const handleStart = async () => {
  if (!fileList.value || fileList.value.length === 0) {
    console.log('请先选择文件');
    return;
  }
  uploading.value = true
  try {
    if (fileList.value.length > 1) {
      console.log('批量上传');
      const promises = fileList.value.map((file) => {
        const uploadFile = file; // 获取 UploadFile 对象
        const originalFile = uploadFile.originFileObj; // 提取原生 File 对象
        if (!originalFile) {
          console.error('无法获取原生 File 对象');
          return;
        }
        console.log('上传文件:', originalFile); // 验证是否为 File 对象
        return createDetectionUsingPost({ sourceType: 'upload' }, originalFile);
      })
      await Promise.all(promises)
      uploading.value = false
      await router.push({ name: 'HistoryRecord' });
    }else{
      console.log('单张上传');
      const uploadFile = fileList.value[0]; // 获取 UploadFile 对象
      const originalFile = uploadFile.originFileObj; // 提取原生 File 对象
      if (!originalFile) {
        console.error('无法获取原生 File 对象');
        return;
      }
      console.log('上传文件:', originalFile); // 验证是否为 File 对象
      const res = await createDetectionUsingPost({ sourceType: 'upload' }, originalFile);
      console.log('上传结果:', res);

      await router.push({ name: 'DefectDetail', params: { id: res.data.id } });
    }
  } catch (error) {
    console.error('上传失败:', error);
  }
};



// 文件列表
const fileList = ref<any[]>([])

// 轮播控制
const carouselRef = ref<typeof Carousel>()
const currentSlide = ref(0)

// 文件上传逻辑
const handleChange = (info: any) => {
  console.log('上传信息:', info)
}

const beforeUpload = (file: any) => {
  console.log('文件:', file)
  return false
}

const getImageUrl = (file: any) => {
  if (file.url) return file.url
  if (file.originFileObj) return URL.createObjectURL(file.originFileObj)
  return ''
}


// 轮播导航逻辑
const handlePrev = () => {
  carouselRef.value?.prev()
}

const handleNext = () => {
  carouselRef.value?.next()
}

const handleSlideChange = (current: number) => {
  currentSlide.value = current
}
</script>

<style scoped>
.left-section, .right-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.upload-section {
  flex: 1;
  padding: 40px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 12px;
  text-align: center;
}

.start-button {
  margin-top: 20px;
  text-align: right;
}

.preview-section {
  height: 100%;
  position: relative;
}

.empty-preview {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 单图样式 */
.single-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
}

/* 轮播控件样式 */
.carousel-controls {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  z-index: 2;
}

.nav-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

  &:hover {
    background: rgba(255, 255, 255, 1);
  }

  &[disabled] {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.pagination {
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
}

/* 轮播项样式 */
.carousel-item {
  height: 340px; /* 为底部控件留出空间 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  height: 100%;
  width: 100%;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
}
.css-dev-only-do-not-override-1p3hq3p .ant-upload-wrapper .ant-upload-list .ant-upload-list-item .ant-upload-list-item-name {
  overflow: hidden;
  white-space: normal; /* Allow text to wrap instead of nowrap */
  text-overflow: ellipsis; /* Keep ellipsis for single-line overflow */
  padding: 0 12px; /* Increase padding for better spacing */
  line-height: 1.8; /* Increase line height for better readability */
  flex: 1 1 auto; /* Allow flex to grow and shrink appropriately */
  transition: all 0.3s;
  max-width: 100%; /* Ensure it doesn't exceed container width */
  word-break: break-all; /* Break long words to prevent overflow */
}

/* Optional: Show full text on hover */
.css-dev-only-do-not-override-1p3hq3p .ant-upload-wrapper .ant-upload-list .ant-upload-list-item .ant-upload-list-item-name:hover {
  overflow: visible; /* Show full text on hover */
  white-space: normal; /* Allow wrapping on hover */
  text-overflow: clip; /* Remove ellipsis on hover */
}
</style>
